import React, { Fragment, useState } from "react";
import GridLayout, {
  Responsive as ResponsiveGridLayout,
} from "react-grid-layout";
import "react-grid-layout/css/styles.css";
import "react-resizable/css/styles.css";
import "./App.css";
import { findObjFromArray } from "./util/tool";

function App() {
  const renderGridLines = () => {
    const cols = 60; // 列数
    const rowHeight = 30; // 行高
    const width = 1200; // 容器宽度
    const colWidth = width / cols; // 每列宽度

    const clientHeight = document.documentElement.clientHeight;
    const lineNums = clientHeight / (width / cols);

    const lines = [];
    for (let i = 0; i <= cols; i++) {
      lines.push(
        <div
          key={`col-${i}`}
          style={{
            position: "absolute",
            left: i * colWidth,
            top: 0,
            width: 1,
            height: "100%",
            backgroundColor: "#ccc",
          }}
        />
      );
    }
    for (let i = 0; i <= lineNums; i++) {
      lines.push(
        <div
          key={`row-${i}`}
          style={{
            position: "absolute",
            left: 0,
            top: i * colWidth,
            width: "100%",
            height: 1,
            backgroundColor: "#ccc",
          }}
        />
      );
    }
    return lines;
  };

  const componentOne = (key) => {
    return (
      <div key={key}>
        <div className="block-bar">
          <div className="block-bar-left">
            <img
              src={new URL("./assets/img/21.png", import.meta.url)}
              className="block-bar__img"
            />
            <p className="block-bar-title">此处为栏目标题</p>
          </div>
          <div className="block-bar-more">
            更多
            <img
              src={new URL("./assets/img/23.png", import.meta.url)}
              className="block-bar-more__icon"
            />
          </div>
        </div>
      </div>
    );
  };

  const componentTwo = (key) => {
    return (
      <div key={key}>
        <div class="block-list-box">
          <div class="block-list">
            <div class="block-list-left">
              <span class="block-list-dot"></span>
              <p class="block-list-title">滨江区召开全区公安工作会议</p>
            </div>
            <p class="block-list-time">11-27</p>
          </div>
          <div class="block-list">
            <div class="block-list-left">
              <span class="block-list-dot"></span>
              <p class="block-list-title">滨江区召开全区公安工作会议</p>
            </div>
            <p class="block-list-time">11-27</p>
          </div>
        </div>
      </div>
    );
  };

  const generateHTML = () => {
    // const { layout } = this.state;
    const gridWidth = 1200; // 网格总宽度
    const cols = 60; // 列数
    const rowHeight = 20; // 行高

    // 计算每个网格项的宽度和位置
    const gridItems = layout.map((item) => {
      const width = (item.w / cols) * gridWidth;
      const height = item.h * rowHeight;
      const left = (item.x / cols) * gridWidth;
      const top = item.y * rowHeight;
      console.log(item);
      return `
        <div
          key="${item.i}"
          style="
            position: absolute;
            width: ${width}px;
            height: ${height}px;
            left: ${left}px;
            top: ${top}px;
            border: 1px solid #ccc;
            box-sizing: border-box;
          "
        >
          ${item.i}
        </div>
      `;
    });

    // 组合成完整的 HTML
    const html = `
      <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Exported Grid Layout</title>
        <style>
        * {
          margin: 0;
          padding: 0;
        }
          .grid-container {
            position: relative;
            width: ${gridWidth}px;
            height: ${
              Math.max(...layout.map((item) => item.y + item.h)) * rowHeight
            }px;
          }
        </style>
      </head>
      <body>
        <div class="grid-container">
          ${gridItems.join("")}
        </div>
      </body>
      </html>
    `;
    console.log("html...", html);
    return html;
  };

  const [layout, setLayout] = useState([
    {
      i: "a",
      x: 0,
      y: 0,
      w: 2,
      h: 2,
      type: "p",
      innerLayout: [
        { i: "d", x: 0, y: 0, w: 2, h: 2, type: "p" },
        { i: "e", x: 0, y: 0, w: 2, h: 2, type: "p" },
      ],
    }, // 组件 a
    { i: "b", x: 2, y: 0, w: 2, h: 4, type: "div" }, // 组件 b
    { i: "c", x: 4, y: 0, w: 6, h: 6, type: "p" }, // 组件 c
    {
      i: "g",
      x: 8,
      y: 0,
      w: 6,
      h: 6,
      type: "component",
      typeName: "componentOne",
    },
    {
      i: "h",
      x: 10,
      y: 10,
      w: 10,
      h: 6,
      type: "component",
      typeName: "componentTwo",
    },
  ]);
  // const layout = [
  //   {
  //     i: "a",
  //     x: 0,
  //     y: 0,
  //     w: 2,
  //     h: 2,
  //     type: "p",
  //     innerLayout: [
  //       { i: "d", x: 0, y: 0, w: 2, h: 2, type: "p" }, // 组件 c
  //     ],
  //   }, // 组件 a
  //   { i: "b", x: 2, y: 0, w: 2, h: 4, type: "div" }, // 组件 b
  //   { i: "c", x: 4, y: 0, w: 6, h: 6, type: "p" }, // 组件 c
  // ];

  const innerLayout = [
    { i: "d", x: 4, y: 0, w: 2, h: 2 }, // 组件 c
  ];

  const handleDragStatrt = (e) => {
    console.log(e);
  };

  const handleResizeStart = (e) => {
    console.log(e);
  };

  const handleResizeStop = (
    layoutData,
    oldItem,
    newItem,
    placeholder,
    e,
    ele
  ) => {
    // console.log(layout);
    // console.log(oldItem);
    // console.log(newItem);
    // console.log(ele);
    //newItem 未更改后的数据
    //当前resize的dom的i
    const i = newItem["i"];
    //获取这个obj
    const obj = findObjFromArray("i", newItem["i"], "innerLayout", layout);

    obj.w = newItem.w;
    obj.h = newItem.h;
    obj.x = newItem.x;
    obj.y = newItem.y;
    // generateHTML();
  };

  const handleDragStop = (a, oldItem, newItem) => {
    const obj = findObjFromArray("i", newItem["i"], "innerLayout", layout);
    obj.w = newItem.w;
    obj.h = newItem.h;
    obj.x = newItem.x;
    obj.y = newItem.y;
  };

  const renderDomCycle = (dom) => {
    // const base = `<div key="${dom.key}"></div>`
    let content = "";
    if (dom.innerLayout) {
      const backCon = renderDom(dom.innerLayout);
      content = (
        <GridLayout
          className="nested-layout"
          layout={dom.innerLayout}
          cols={4} // 内层列数
          rowHeight={20}
          width={dom.w * 20} // 内层宽度（外层网格项宽度）
          margin={[0, 0]}
          compactType={null}
          isDraggable={true}
          isResizable={true}
          onDragStop={handleDragStop}
          onResizeStart={handleResizeStart}
          onResizeStop={handleResizeStop}
        >
          {backCon}
        </GridLayout>
      );
    }

    let html = "";
    if (dom.type == "component") {
      if (dom.typeName == "componentOne") {
        html = componentOne(dom["i"]);
      } else if (dom.typeName == "componentTwo") {
        html = componentTwo(dom["i"]);
      }
    } else {
      html = <div key={dom.i}>{content}</div>;
    }
    return html;
  };

  // console.log(renderDomCycle(layout[0]));
  const renderDom = (innerLayout) => {
    const layoutData = innerLayout || layout;
    const domState = [];
    layoutData.forEach((item, index) => {
      const domJsx = renderDomCycle(item);
      domState.push(domJsx);
      // console.log(domState);
      // return (
      //   domState.map(v => v)
      // )
    });

    return domState.map((v) => v);
  };

  const handleAdd = () => {
    const layoutCopy = JSON.parse(JSON.stringify(layout));
    layoutCopy.push({
      i: 'l',
      x: 10,
      y: 10,
      w: 10,
      h: 6,
      type: "component",
      typeName: "componentOne",
    });
    setLayout(layoutCopy);
  };

  // console.log(generateHTML());

  return (
    <>
      <div className="container" style={{ position: "relative" }}>
        {renderGridLines()}
        <GridLayout
          className="layout"
          layout={layout}
          cols={60} // 列数
          rowHeight={20} // 每行高度
          width={1200} // 容器宽度
          margin={[0, 0]}
          compactType={null}
          isDraggable={true}
          isResizable={true}
          onDragStop={handleDragStop}
          onResizeStart={handleResizeStart}
          onResizeStop={handleResizeStop}
        >
          {renderDom()}
          {/* <p key="a" style={{ background: "#f0f0f0" }}>
          A
        </p>
        <p key="b" style={{ background: "#d9d9d9" }}>
          B
        </p>
        <div key="c" style={{ background: "#e0e0e0" }}>
          C
          <GridLayout
            className="nested-layout"
            layout={innerLayout}
            cols={4} // 内层列数
            rowHeight={30}
            width={150} // 内层宽度（外层网格项宽度）
            margin={[0, 0]}
            compactType={null}
            isDraggable={true}
            isResizable={true}
          >
            <div key="d" style={{ background: "#e0e0e0" }}>
              D
            </div>
          </GridLayout>
        </div> */}
        </GridLayout>
      </div>
      <button type="button" onClick={generateHTML}>
        generate
      </button>
      <button type="button" onClick={handleAdd}>
        新增
      </button>
    </>
  );
}

export default App;
